import { Layout } from "@/router/index.ts";
import { IRouter } from "@/utils/types/TMenu.ts";

export const basicRouteMap = {
  // 空页面
  ComponentError: () => import("@/layouts/exception/componentError.vue"),
};
const pages = import.meta.glob("/src/views/**/*.vue");
const resolveComponent = (name: string) => {
  const importPage = pages[`/src/views/${name}.vue`];
  if (!importPage) {
    return basicRouteMap.ComponentError;
  }
  if (typeof importPage === "object" && "default" in importPage) {
    // @ts-ignore
    return importPage.default;
  }
  return importPage;
};

export function getMenuModule(asyncRouterMap: IRouter[]) {
  return asyncRouterMap.filter((route: IRouter) => {
    if (route.component === "Layout") {
      route.component = Layout;
    } else {
      if (route.name !== "home") {
        route.path = `${route.path}`;
        // @ts-ignore
        route.component = resolveComponent(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = getMenuModule(route.children);
    }
    return true;
  });
}

export function getRouterModule(asyncRouter: IRouter[]) {
  const routes: IRouter[] = [];
  function aa(_routes: IRouter[]) {
    _routes.forEach((route: IRouter) => {
      if (route.children != null && route.children && route.children.length) {
        aa(route.children);
      } else {
        routes.push(route);
      }
    });
  }
  aa(asyncRouter);
  return routes;
}
